import lib
import threading
import requests
from PIL import Image, ImageTk
from io import BytesIO
import tkinter as tk
import time
from urllib.parse import urljoin



Library = lib.AddonsLibrary('Desktop_pp')

class DesktopViewer:
    def __init__(self, root):
        self.root = root
        self.root.title("Desktop Viewer")
        
        # 初始化变量
        self.image = None
        self.photo = None
        self.running = True
        self.last_x = 0
        self.last_y = 0
        
        # 创建显示窗口
        self.canvas = tk.Canvas(root)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        
        # 绑定鼠标事件
        self.canvas.bind("<Motion>", self.on_mouse_move)
        self.canvas.bind("<Button-1>", lambda e: self.on_mouse_click("left"))
        self.canvas.bind("<Button-2>", lambda e: self.on_mouse_click("mid"))
        self.canvas.bind("<Button-3>", lambda e: self.on_mouse_click("right"))
        
        # 启动下载线程
        self.download_thread = threading.Thread(target=self.download_loop, daemon=True)
        self.download_thread.start()
        
        # 处理窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
    
    def download_loop(self):
        """循环下载图像并更新UI"""
        while self.running:
            try:
                # 下载图像
                response = requests.get(f"http://{URL}/Desktop", timeout=5)
                response.raise_for_status()
                
                # 处理图像
                image_data = BytesIO(response.content)
                self.image = Image.open(image_data)
                
                # 在主线程中更新UI
                self.root.after(0, self.update_display)
                
            except Exception as e:
                print(f"下载错误: {e}")
                time.sleep(1)  # 出错时等待一秒再重试
    
    def update_display(self):
        """更新显示的图像"""
        if self.image:
            # 调整图像大小以适应窗口
            canvas_width = self.canvas.winfo_width()
            canvas_height = self.canvas.winfo_height()
            
            if canvas_width > 0 and canvas_height > 0:
                # 保持宽高比缩放
                img_width, img_height = self.image.size
                ratio = min(canvas_width / img_width, canvas_height / img_height)
                new_size = (int(img_width * ratio), int(img_height * ratio))
                
                resized_img = self.image.resize(new_size, Image.LANCZOS)
                self.photo = ImageTk.PhotoImage(image=resized_img)
                
                # 清除画布并显示新图像
                self.canvas.delete("all")
                self.canvas.create_image(
                    canvas_width // 2, 
                    canvas_height // 2, 
                    image=self.photo
                )
    
    def on_mouse_move(self, event):
        """处理鼠标移动事件"""
        x, y = event.x, event.y
        
        # 避免频繁发送相同坐标
        if abs(x - self.last_x) > 2 or abs(y - self.last_y) > 2:
            self.last_x, self.last_y = x, y
            # 在新线程中发送请求，避免阻塞UI
            threading.Thread(
                target=self.send_mouse_move, 
                args=(x, y), 
                daemon=True
            ).start()
    
    def on_mouse_click(self, button):
        """处理鼠标点击事件"""
        # 在新线程中发送请求，避免阻塞UI
        threading.Thread(
            target=self.send_mouse_click, 
            args=(button,), 
            daemon=True
        ).start()
    
    def send_mouse_move(self, x, y):
        """发送鼠标移动坐标到服务器"""
        try:
            url = f"http://{URL}/Desktop/movm/{x}/{y}"
            requests.get(url, timeout=2)
        except Exception as e:
            print(f"发送鼠标移动错误: {e}")
    
    def send_mouse_click(self, button):
        """发送鼠标点击事件到服务器"""
        try:
            url = f"http://{URL}/Desktop/m/{button}"
            requests.get(url, timeout=2)
        except Exception as e:
            print(f"发送鼠标点击错误: {e}")
    
    def on_close(self):
        """处理窗口关闭事件"""
        self.running = False
        self.root.destroy()


def Desktop_ppInit():
    pass


def Desktop_ppMain():
    Desktop_ppInit()
    root = tk.Tk()
    app = DesktopViewer(root)
    root.mainloop()


if __name__ == "__main__":
    Desktop_ppMain()
